/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;


import com.google.common.base.Splitter;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.bean.IndexTemplateConfigBean;
import com.koron.purpose.domain.KPITemplate;
import com.koron.purpose.mapper.IndexTemplateConfigMapper;
import com.koron.purpose.mapper.KPITemplateMapper;
import com.koron.purpose.service.api.IndexTemplateConfigService;
import com.koron.purpose.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;

@SuppressWarnings("deprecation")
@Service
public class IndexTemplateConfigServiceImpl implements IndexTemplateConfigService {
    private final static Logger logger= LoggerFactory.getLogger(IndexTemplateConfigServiceImpl.class);

    @Override
    public MessageBean queryForList(String corpCode, Integer yearNum, String indexName, Integer page, Integer pageSize) {
        MessageBean<DataBean<Map>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            IndexTemplateConfigMapper mapper = factory.getMapper(IndexTemplateConfigMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("corpCode", corpCode);
            map.put("yearNum", yearNum);
            map.put("indexName", indexName);
            if (page != null || pageSize != null){
                page = (page == null || page < 1) ? 1 : page;
                pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
                int pageStart = (page - 1) * pageSize;
                map.put("pageStart", pageStart);
                map.put("pageSize", pageSize);
            }
            List<Map> list = mapper.queryForList(map);
            DataBean<Map> dataBean = new DataBean<>();
            dataBean.setList(list);
            if (page != null || pageSize != null){
                dataBean.setPageSize(pageSize);
                dataBean.setPageNo(page);
                // 总条数
                Integer totalNumber = mapper.countQueryForList(map);
                int num = totalNumber / pageSize;
                // 总页数
                Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
                dataBean.setTotalNumber(totalNumber);
                dataBean.setTotalPage(totalPage);
            }
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean queryById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            IndexTemplateConfigMapper mapper = factory.getMapper(IndexTemplateConfigMapper.class);
            // 查询
            Map bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("未查到该指标模版配置");
                return msg;
            }
            // 查询指标列表信息
            List<KPITemplate> kpiTemplates = factory.getMapper(KPITemplateMapper.class).queryByCondition(null, null, null, null, null);
            // 根据指标模版id 查询 指标模版配置管理记录
            List<Map<String, Object>> indexConfigKpis = mapper.queryIndexConfigKpis(id);
            List<Map> list = new LinkedList<>();
            indexConfigKpis.stream().forEach(m -> {
                String kpiTemplateId = m.get("kpiTemplateId").toString();
                kpiTemplates.stream().forEach(kpiTemplate -> {
                    if (kpiTemplateId.equals(kpiTemplate.getId())) {
                        m.put("year", kpiTemplate.getYear());
                        m.put("name", kpiTemplate.getName());
                        m.put("rule", kpiTemplate.getRule());
                        m.put("val", kpiTemplate.getVal());
                        m.put("negatively", Integer.valueOf(kpiTemplate.getNegatively()));
                        m.put("note", kpiTemplate.getNote());
                        // 满足 责任书制定格式
                        m.put("itemId", kpiTemplate.getId());
                        m.put("itemName", kpiTemplate.getName());
                        m.put("itemValue", kpiTemplate.getVal());
                        list.add(m);
                        return;
                    }
                });
            });
            bean.put("kpiTemplates", list);
            msg.setData(bean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean deleteById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            IndexTemplateConfigMapper mapper = factory.getMapper(IndexTemplateConfigMapper.class);
            Map bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该指标模版配置已被删除");
                factory.close(false);
                return msg;
            }
            // 根据id 删除 指标模版配置
            if (mapper.deleteIndexTemplateConfig(id) != 1) {
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("删除失败!");
                factory.close(false);
            }
            // 根据指标模版id 删除 指标模版配置管理表记录
            mapper.deleteIndexConfigKpi(id);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean insert(StaffBean user, IndexTemplateConfigBean bean, String kpiTemplateIds) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "新增成功", void.class);
        // 参数校验
        if (bean.getYearNum() == null || bean.getYearNum() < 1000 || StringUtils.isEmpty(bean.getCorpCode())
                || StringUtils.isEmpty(bean.getCorpName()) || StringUtils.isEmpty(bean.getIndexName())) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        List<String> kpiTemplateIdList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(kpiTemplateIds);
        if (kpiTemplateIdList == null || kpiTemplateIdList.size() < 1){
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription("请选择要进行配置的指标");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            Date date = new Date();
            bean.setAddUser(user.getCode());
            bean.setAddUserName(user.getName());
            bean.setAddTime(date);
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(date);
            String id = DefaultIdGenerator.getInstance().generateLongId();
            bean.setId(id);
            IndexTemplateConfigMapper mapper = factory.getMapper(IndexTemplateConfigMapper.class);
            // 新增 指标模版配置
            mapper.insertIndexTemplateConfig(bean);
            // 新增 指标模版配置管理表
            List<Map> indexConfigKpis = new LinkedList<>();
            Map<String, String> map;
            for (String kpiTemplateId : kpiTemplateIdList){
                map = new HashMap<>();
                map.put("indexTemplateConfigId", id);
                map.put("kpiTemplateId", kpiTemplateId);
                indexConfigKpis.add(map);
            }
            // 批量新增 指标模版配置管理表
            mapper.insertBatchIndexConfigKpi(indexConfigKpis);
            // 关闭
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean update(StaffBean user, IndexTemplateConfigBean bean, String kpiTemplateIds) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "修改成功", void.class);
        // 参数校验
        if (bean.getYearNum() == null || bean.getYearNum() < 1000 || StringUtils.isEmpty(bean.getCorpCode())
                || StringUtils.isEmpty(bean.getCorpName()) || StringUtils.isEmpty(bean.getIndexName())) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }

        List<String> kpiTemplateIdList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(kpiTemplateIds);
        if (kpiTemplateIdList == null || kpiTemplateIdList.size() < 1){
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription("请选择要进行配置的指标");
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            Date date = new Date();
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(date);
            IndexTemplateConfigMapper mapper = factory.getMapper(IndexTemplateConfigMapper.class);
            // 修改 指标模版配置
            if (mapper.updateIndexTemplateConfig(bean) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("修改失败");
                return msg;
            }
            // 根据 指标模版配置id 删除 指标模版配置管理表记录
            mapper.deleteIndexConfigKpi(bean.getId());
            // 新增 指标模版配置管理表
            List<Map> indexConfigKpis = new LinkedList<>();
            Map<String, String> map;
            for (String kpiTemplateId : kpiTemplateIdList){
                map = new HashMap<>();
                map.put("indexTemplateConfigId", bean.getId());
                map.put("kpiTemplateId", kpiTemplateId);
                indexConfigKpis.add(map);
            }
            // 批量新增 指标模版配置管理表
            mapper.insertBatchIndexConfigKpi(indexConfigKpis);
            // 关闭
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }
}
